<template>
  <div class="min-h-screen bg-base-100">
    <div class="blog-container">
      <h1 class="text-3xl font-bold mb-8">导入导出</h1>
      
      <div class="grid md:grid-cols-2 gap-8">
        <!-- 导出数据 -->
        <div class="card bg-base-100 shadow-xl border border-base-200">
          <div class="card-body">
            <h2 class="card-title text-2xl mb-4">
              <icon-heroicons-arrow-up-tray class="w-6 h-6 mr-2" />
              导出数据
            </h2>
            
            <p class="mb-6">导出您的博客数据，方便备份或迁移到其他设备。</p>
            
            <div class="space-y-4">
              <div class="form-control">
                <label class="label cursor-pointer justify-start gap-2">
                  <input type="checkbox" class="checkbox" v-model="exportOptions.includeDrafts" />
                  <span class="label-text">包含草稿</span>
                </label>
              </div>
              
              <div class="form-control">
                <label class="label cursor-pointer justify-start gap-2">
                  <input type="checkbox" class="checkbox" v-model="exportOptions.includeSettings" />
                  <span class="label-text">包含设置</span>
                </label>
              </div>
              
              <div class="form-control">
                <label class="label cursor-pointer justify-start gap-2">
                  <input type="checkbox" class="checkbox" v-model="exportOptions.prettyPrint" />
                  <span class="label-text">美化 JSON 格式</span>
                </label>
              </div>
            </div>
            
            <div class="card-actions justify-end mt-6">
              <button @click="exportData" class="btn btn-primary gap-2">
                <icon-heroicons-arrow-down-tray class="w-5 h-5" />
                导出数据
              </button>
            </div>
          </div>
        </div>
        
        <!-- 导入数据 -->
        <div class="card bg-base-100 shadow-xl border border-base-200">
          <div class="card-body">
            <h2 class="card-title text-2xl mb-4">
              <icon-heroicons-arrow-down-tray class="w-6 h-6 mr-2" />
              导入数据
            </h2>
            
            <p class="mb-6">从文件导入博客数据，或批量导入多篇文章。</p>
            
            <div class="space-y-6">
              <div class="space-y-2">
                <div class="flex items-center justify-between mb-2">
                  <h3 class="font-bold">导入备份文件</h3>
                  <div class="tooltip tooltip-left" data-tip="导入将会覆盖当前数据">
                    <icon-heroicons-exclamation-circle class="w-5 h-5 text-warning" />
                  </div>
                </div>
                
                <div class="flex gap-2">
                  <input 
                    type="file" 
                    accept=".json" 
                    class="file-input file-input-bordered w-full"
                    @change="handleFileChange" />
                  <button 
                    @click="importData" 
                    class="btn btn-primary" 
                    :disabled="!selectedFile">
                    导入
                  </button>
                </div>
              </div>
              
              <div class="divider my-4">或者</div>
              
              <div class="space-y-2">
                <h3 class="font-bold mb-2">批量导入文章</h3>
                <div class="flex gap-2">
                  <input 
                    type="file" 
                    accept=".json" 
                    multiple
                    class="file-input file-input-bordered w-full"
                    @change="handleMultipleFileChange" />
                  <button 
                    @click="importMultipleData" 
                    class="btn btn-primary" 
                    :disabled="!selectedMultipleFiles.length">
                    导入
                  </button>
                </div>
                <p class="text-sm text-base-content/70">
                  您可以同时选择多个 JSON 文件进行批量导入
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 导入导出历史 -->
      <div class="mt-12">
        <h2 class="text-2xl font-bold mb-6">导入导出历史</h2>
        
        <div v-if="importExportHistory.length > 0" class="overflow-x-auto">
          <table class="table">
            <thead>
              <tr>
                <th>操作类型</th>
                <th>日期时间</th>
                <th>文件数量</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(history, index) in importExportHistory" :key="index" class="hover">
                <td>{{ history.type === 'import' ? '导入' : '导出' }}</td>
                <td>{{ formatDate(history.date) }}</td>
                <td>{{ history.fileCount }}</td>
                <td>
                  <span 
                    class="badge" 
                    :class="{
                      'badge-success': history.status === 'success',
                      'badge-error': history.status === 'error'
                    }">
                    {{ history.status === 'success' ? '成功' : '失败' }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div v-else class="text-center py-8 bg-base-200 rounded-lg">
          <p>暂无导入导出历史记录</p>
        </div>
      </div>
    </div>
    
    <!-- 导入确认模态框 -->
    <dialog :class="{ 'modal-open': showImportConfirm }" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">确认导入</h3>
        <p class="py-4 text-warning">
          <icon-alert-triangle class="w-6 h-6 inline-block mr-2" />
          导入操作将会覆盖当前的数据，此操作不可撤销。
        </p>
        <p class="mb-4">您确定要继续吗？</p>
        <div class="modal-action">
          <button @click="cancelImport" class="btn">取消</button>
          <button @click="confirmImport" class="btn btn-primary">确认导入</button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button @click="cancelImport">取消</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useBlogStore } from '@/stores/blogStore';
import { useSettingsStore } from '@/stores/settingsStore';
import type { BlogPost, BlogExport } from '@/types';

const blogStore = useBlogStore();
const settingsStore = useSettingsStore();

// 导出选项
const exportOptions = reactive({
  includeDrafts: true,
  includeSettings: true,
  prettyPrint: true,
});

// 导入文件
const selectedFile = ref<File | null>(null);
const selectedMultipleFiles = ref<File[]>([]);
const showImportConfirm = ref(false);
const importType = ref<'single' | 'multiple'>('single');

// 导入导出历史
const importExportHistory = ref<Array<{
  type: 'import' | 'export';
  date: string;
  fileCount: number;
  status: 'success' | 'error';
}>>([]);

// 处理文件选择
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    selectedFile.value = input.files[0];
  }
};

// 处理多文件选择
const handleMultipleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    selectedMultipleFiles.value = Array.from(input.files);
  }
};

// 导出数据
const exportData = () => {
  try {
    // 准备导出数据
    const exportData: any = {};
    
    // 导出博客数据
    const posts = exportOptions.includeDrafts 
      ? blogStore.getAllPosts 
      : blogStore.getPublishedPosts;
    
    exportData.posts = posts;
    exportData.tags = blogStore.tags;
    
    // 可选地包含设置
    if (exportOptions.includeSettings) {
      exportData.settings = {
        theme: settingsStore.theme,
        editorType: settingsStore.editorType,
        fontSize: settingsStore.fontSize,
        language: settingsStore.language,
      };
    }
    
    // 转换为 JSON
    const jsonData = exportOptions.prettyPrint 
      ? JSON.stringify(exportData, null, 2) 
      : JSON.stringify(exportData);
    
    // 创建并下载文件
    const blob = new Blob([jsonData], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `blog-export-${new Date().toISOString().slice(0, 10)}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    // 添加历史记录
    importExportHistory.value.unshift({
      type: 'export',
      date: new Date().toISOString(),
      fileCount: 1,
      status: 'success',
    });
  } catch (error) {
    console.error('导出失败:', error);
    alert('导出数据失败，请重试');
    
    // 添加失败记录
    importExportHistory.value.unshift({
      type: 'export',
      date: new Date().toISOString(),
      fileCount: 1,
      status: 'error',
    });
  }
};

// 导入数据（先显示确认对话框）
const importData = () => {
  if (!selectedFile.value) return;
  
  importType.value = 'single';
  showImportConfirm.value = true;
};

// 批量导入数据（先显示确认对话框）
const importMultipleData = () => {
  if (selectedMultipleFiles.value.length === 0) return;
  
  importType.value = 'multiple';
  showImportConfirm.value = true;
};

// 确认导入
const confirmImport = () => {
  if (importType.value === 'single') {
    if (!selectedFile.value) return;
    
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result as string);
        
        // 导入数据
        if (data.posts) {
          blogStore.importData({
            posts: data.posts,
            tags: data.tags || [],
          });
        }
        
        // 导入设置
        if (data.settings) {
          settingsStore.setTheme(data.settings.theme || 'light');
          settingsStore.setEditorType(data.settings.editorType || 'markdown');
          settingsStore.setFontSize(data.settings.fontSize || 16);
          settingsStore.setLanguage(data.settings.language || 'zh-CN');
        }
        
        alert('数据导入成功');
        
        // 添加历史记录
        importExportHistory.value.unshift({
          type: 'import',
          date: new Date().toISOString(),
          fileCount: 1,
          status: 'success',
        });
      } catch (error) {
        console.error('导入失败:', error);
        alert('导入数据失败，文件格式可能不正确');
        
        // 添加失败记录
        importExportHistory.value.unshift({
          type: 'import',
          date: new Date().toISOString(),
          fileCount: 1,
          status: 'error',
        });
      }
    };
    
    reader.readAsText(selectedFile.value);
  } else {
    // 批量导入
    let successCount = 0;
    let failCount = 0;
    
    const promises = selectedMultipleFiles.value.map(file => {
      return new Promise<void>((resolve) => {
        const reader = new FileReader();
        
        reader.onload = (e) => {
          try {
            const data = JSON.parse(e.target?.result as string);
            
            // 如果是单篇文章
            if (data.title && data.content) {
              blogStore.addPost(data);
              successCount++;
            } 
            // 如果是文章数组
            else if (Array.isArray(data)) {
              blogStore.importPosts(data);
              successCount += data.length;
            }
            // 如果是导出格式
            else if (data.posts) {
              blogStore.importPosts(data.posts);
              successCount += data.posts.length;
            } else {
              failCount++;
            }
          } catch (error) {
            console.error(`导入文件 ${file.name} 失败:`, error);
            failCount++;
          }
          
          resolve();
        };
        
        reader.readAsText(file);
      });
    });
    
    Promise.all(promises).then(() => {
      alert(`批量导入完成。成功: ${successCount} 篇，失败: ${failCount} 篇`);
      
      // 添加历史记录
      importExportHistory.value.unshift({
        type: 'import',
        date: new Date().toISOString(),
        fileCount: selectedMultipleFiles.value.length,
        status: failCount === 0 ? 'success' : 'error',
      });
    });
  }
  
  // 关闭确认对话框
  showImportConfirm.value = false;
};

// 取消导入
const cancelImport = () => {
  showImportConfirm.value = false;
};

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};
</script> 